package com.example.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.admin.mapper.UserMapper;
import com.example.admin.service.UserService;
import com.example.common.util.R;
import com.example.common.util.ResultCodeRecord;
import com.example.model.admin.dto.UserDto;
import com.example.model.admin.pojo.User;
import com.example.utils.common.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl< UserMapper, User > implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, Object> login(UserDto userDto) {
        Map<String, Object> map = new HashMap<>();
        // 1、正常登录 用户名、密码
        if (StringUtils.isNotBlank(userDto.getUserName()) && StringUtils.isNotBlank(userDto.getPassword())) {
            R.error(ResultCodeRecord.AP_USER_DATA_NOT_EXIST, "管理员不存在");
        }
        // 2、查询用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, userDto.getUserName());
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            R.error(ResultCodeRecord.DATA_NOT_EXIST, "密码错误");
        }
        // 3、验证密码
        String userSalt = user.getUserSalt();
        String password = userDto.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex((password + userSalt).getBytes());
        if (md5Password.equals(user.getPassword())) {
            // 4、返回数据
            user.setUserSalt(null);
            user.setPassword(null);
            map.put("user", user);
            map.put("token", JwtUtil.getToken(user.getUserId().longValue()));
            return map;
        } else {
            R.error(ResultCodeRecord.LOGIN_PASSWORD_ERROR, "管理员或者密码不正确");
            return map;
        }
    }
}
